package com.whz.work.ex01;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @ClassName HttpServer
 * @Description TODO HttpServer表示一个Web服务器
 * @Author hong-zhi
 * @Date 2021/5/27 18:20
 * @Version 1.0
 */
@Slf4j
public class HttpServer {
    /*当前项目所在的路径 + \webroot*/
    public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot";
    /*shutdown命令*/
    private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
    /*是否接收到shutdown命令*/
    private boolean shutdown = false;

    public static void main(String[] args) {
        HttpServer server = new HttpServer();
        server.await();
    }
    public void await() {
        ServerSocket serverSocket = null;
        int port = 8888;
        try  {
            serverSocket =
                    new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));

            while (!shutdown) {

                Socket socket = null;
                InputStream input = null;
                OutputStream output = null;
                try {
                    socket = serverSocket.accept();
                    //从socket中获取到InputStream 和 OutputStream
                    input = socket.getInputStream();
                    output = socket.getOutputStream();
                    Request request = new Request(input);
                    request.parse();

                    Response response = new Response(output);
                    response.setRequest(request);
                    response.sendStaticResource();

                    socket.close();

                    shutdown = StringUtils.equals(request.getUri(), SHUTDOWN_COMMAND);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }





            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
            System.exit(1);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }

    }
}
